package com.aistar.service.impl;

import com.aistar.mapper.MessageMapper;
import com.aistar.pojo.Message;
import com.aistar.pojo.MessageExample;
import com.aistar.service.MessageService;
import com.aistar.util.MessageUtil;
import com.aistar.util.ServerResponse;
import com.aistar.util.WebSocketServerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    private final MessageMapper messageMapper;

    @Autowired
    public MessageServiceImpl(MessageMapper messageMapper) {
        this.messageMapper = messageMapper;
    }

    @Override
    public ServerResponse getUnreadCountByCustomerId(Integer customerId) {
        MessageExample example = new MessageExample();
        example.createCriteria()
                .andCustomerIdEqualTo(customerId)
                .andStatusEqualTo(MessageUtil.STATUS_SUCCESS);
        int count = messageMapper.countByExample(example);
        return ServerResponse.getSuccess(count);
    }

    @Override
    public ServerResponse getAllByCustomerId(Integer customerId) {
        MessageExample example = new MessageExample();
        example.createCriteria()
                .andCustomerIdEqualTo(customerId)
                .andStatusNotEqualTo(2);
        example.setOrderByClause("message_time desc");
        List<Message> messageList = messageMapper.selectByExample(example);
        if (messageList != null && messageList.size() > 0)
            return ServerResponse.getSuccess(messageList);
        return ServerResponse.getFailed();
    }

    @Override
    public ServerResponse readAllByCustomerId(Integer customerId) {
        Message message = new Message();
        message.setStatus(MessageUtil.STATUS_FAIL);
        MessageExample example = new MessageExample();
        example.createCriteria().andCustomerIdEqualTo(customerId);
        int rows = messageMapper.updateByExampleSelective(message, example);
        if (rows > 0)
            return ServerResponse.modifySuccess();
        return ServerResponse.modifyFailed();
    }

    @Override
    public ServerResponse add(Message message) {
        message.setMessageTime(new Date());
        int rows = messageMapper.insertSelective(message);
        WebSocketServerUtil.sendInfo(message.getCustomerId());
        if (rows > 0)
            return ServerResponse.modifySuccess();
        return ServerResponse.modifyFailed();
    }

    @Override
    public ServerResponse delete(Integer messageId) {
        Message message = new Message();
        message.setMessageId(messageId);
        message.setStatus(2);
        int rows = messageMapper.updateByPrimaryKeySelective(message);
        if (rows > 0)
            return ServerResponse.deleteSuccess();
        return ServerResponse.deleteFailed();
    }
}
